<template>
    <div>
        <div class="wapper" >

            <div class="views-tree tree-container" @dragend="savewfList()">
                <el-tree ref="atreeData"
                    class="tree"
                    :data="atreeData"
                    node-key="id"
                    lazy
                    :load="loadActionNode"
                    :default-expanded-keys="[1]"
                    :default-checked-keys="[1]"
                    :props="defaultProps"
                    :check-on-click-node="false"
                    :expand-on-click-node="false"
                    @node-click="ActionClick"
                    draggable
                    :allow-drop="actionAllowDrop"
                    @node-drop="actionHandleDrop"
                >
                    <span class="custom-tree-node" slot-scope="{ node,data }">
                        <el-button type="text" v-if="node.level == 1" icon="el-icon-plus" @click="addatree(node,true)"></el-button>
                        <span>
                            <i :class="node.icon"></i>
                            {{ node.data.subactionname }}
                        </span>
                        <span>
                            <el-button type="text" v-if="node.data.id > -1" icon="el-icon-plus" @click="addatree(node,false)"></el-button>
                            <el-button type="text" v-if="node.level == 1 && node.data.id > -1" icon="el-icon-edit" @click="editatree(node)"></el-button>
                            <el-button type="text" v-if="node.data.id > -1" icon="el-icon-delete" @click="delatree(node)"></el-button>

                        </span>
                    </span>
                </el-tree>
            </div>

            <div class="info" style="display: none;" id="flagdiv">
                <el-form ref="fform" :model="fform" label-width="20px">
                    <el-form-item>
                        <el-input v-model="fform.id" v-if="false"></el-input>
                        <el-input v-model="fform.servAttrFlag" v-if="false"></el-input>
                        <el-input v-model="fform.regFlag" v-if="false"></el-input>
                        <el-input v-model="fform.subFlag" v-if="false"></el-input>
                        <el-input v-model="fform.sumFlag" v-if="false"></el-input>

                        <el-checkbox-group v-model="flag" @input="change($event)">
                            <el-checkbox label="基本属性" name="flag" @change="checked=>selecteChange(1,checked)"></el-checkbox>
                            <el-checkbox label="注册信息" name="flag" @change="checked=>selecteChange(2,checked)"></el-checkbox>
                            <el-checkbox label="订阅信息" name="flag" @change="checked=>selecteChange(3,checked)"></el-checkbox>
                            <el-checkbox label="汇总信息" name="flag" @change="checked=>selecteChange(4,checked)"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <div style="margin-left: 20px;margin-bottom: 20px">
                        <div style="margin-bottom: 10px">
                            <label style="width: 70px;display:block;text-align:center;color:#ED795A;font-size:14px;">所属模块</label>
                            <input type="text" style="width:80px;text-align:center;border-radius: 5px;border:0.5px solid #ED795A;color:#ED795A;"
                                   v-model="fform.module" @change="selecteChange(0,1)" ></input>
                        </div>
                        <div style="margin-bottom: 10px">
                            <label style="width: 70px;display:block;text-align:center;color:#ED795A;font-size:14px;">依赖资源</label>
                            <input type="text" style="width:80px;text-align:center;border-radius: 5px;border:0.5px solid #ED795A;color:#ED795A;"
                                   v-model="fform.dependentResource"  @change="selecteChange(0,1)" ></input>
                        </div>
                    </div>
                </el-form>
            </div>

            <!-- 子环节编辑弹出框 -->
            <el-dialog title="编辑" :visible.sync="editVisible3" width="30%" :close-on-click-modal="false">
                <el-form ref="aform" :model="aform" label-width="70px">
                    <el-form-item label="子环节名">
                        <el-input v-model="aform.id" v-if="false"></el-input>
                        <el-input v-model="aform.actionid" v-if="false"></el-input>
                        <el-input v-model="aform.seq" v-if="false"></el-input>
                        <el-input v-model="aform.remarks" v-if="false"></el-input>

                        <el-input v-model="aform.subactionname" @input="change($event)"></el-input>
                    </el-form-item>
                    <el-form-item label="子环节编码">
                        <el-input v-model="aform.subactionid" @input="change($event)" :disabled="aform.id != undefined"></el-input>
                    </el-form-item>

                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editVisible3 = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
            </el-dialog>
            <!--end 子环节编辑弹出框 -->

            <!-- 子环节编辑弹出框 -->
            <el-dialog title="编辑" :visible.sync="editVisible4" width="40%" :close-on-click-modal="false">
                <el-form ref="sform" :model="sform" label-width="100px">
                    <el-form-item label="标准服务">
                        <el-input v-model="sform.id" v-if="false"></el-input>
                        <el-input v-model="sform.seq" v-if="false"></el-input>
                        <el-input v-model="sform.subactionid" v-if="false"></el-input>
                        <el-input v-model="sform.remarks" v-if="false"></el-input>
                        <el-input v-model="sform.esbserviceid2" v-if="false"></el-input>
                        <el-select v-model="sform.esbserviceid" filterable remote
                                   :remote-method="remoteMethod"
                                   :loading="loading"
                                   placeholder="请选择关联标准服务" style="width:400px;">
                             <el-option
                                v-for="item in servs"
                                :key="item.esbserviceid"
                                :label="`${item.servname}(${item.servcode}@${item.servversion})`"
                                :value="item.esbserviceid">
                              </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editVisible4 = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit2">确 定</el-button>
                </span>
            </el-dialog>
            <!--end 子环节编辑弹出框 -->
        </div>
    </div>
</template>

<script>
import draggable from 'vuedraggable';
import actionApi from '@/api/action';

export default {
    name: 'vServEdit',
    data() {
        return {
            atreeData: [],
            defaultProps: {
                children: 'children',
                label: 'label',
                isLeaf: 'isLeaf'
            },
            editVisible3: false,
            editVisible4: false,
            editVisible5: false,
            aform: {},
            sform: {},
            fform: {},
            flag: [],
            servs: [],
            module:null,
            dependentResource:null,
            parid: null,
            loading: false,
            remoteTimer: null
        };
    },
    props: ['actionid'],
    components: {
        draggable
    },
    watch: {
        actionid(newValue, oldValue) {
            if (newValue == ''){
                this.atreeData = [];
                var div=document.getElementById("flagdiv");
                div.style.display='none';

            }else if (newValue != oldValue) {
                //this.loadActionNode();
                console.log(`actionid的值发生变化：${newValue} ${oldValue}`);
                this.refresh(newValue);
            }
        }
    },
    methods: {
        change(e){
            this.$forceUpdate();
        },

        refresh(actionid){
            var div=document.getElementById("flagdiv");
            div.style.display='none';

            actionApi.loadtree(actionid,0).then(res => {
                this.atreeData = res.list;
            });
        },

        //加载子环节和服务树
         loadActionNode(node, resolve) {
            console.log(`加载子环节：${this.actionid} ${node.data.id} ${node.data.actionid}`);

            let parId = node.level === 0 ? 0 : node.data.id;
            let actionid = node.level === 0 ? this.actionid : node.data.subactionid;
            if (node.level >=2)
                actionid = node.data.subactionid;

            //if (node.level < 2 &&  parId != -1) {
             if (parId != -1) {
                actionApi.loadtree(actionid,node.level).then(res => {
                    //if (node.level == 1) {
                    if (true) {
                            res.list.forEach(item => {
                                item.isLeaf = false;
                            })
                    }
                    resolve(res.list);
                });
            }else{
                resolve([]);
                var div=document.getElementById("flagdiv");
                div.style.display='none';
            }
         },

        //只允许同级拖拽
        actionAllowDrop(draggingNode, dropNode, type){
            if(draggingNode.level === dropNode.level){
                if(draggingNode.parent.id === dropNode.parent.id){
                    return type === 'prev'
                }
            }else{
                // 不同级进行处理
            }
        },

        //拖拽成功完成时触发的事件，在这里可以将节点拖拽后的顺序返给后端
        actionHandleDrop(node,data,type,event){
            let arr=[];

            //data为拖拽后节点信息，找到它的父级，在从父级找子集
            let child = data.parent.childNodes;
            for(var key in child){
                arr.push(child[key].data);
            }
            //转为JSON字符串发请求带走信息
            //idSort(JSON.stringify(arr))
            console.log(JSON.stringify(arr));
            console.log(node.level);

            if (node.level == 1){
                actionApi.saveActionList(arr).then(res => {
                    if (res.code == 0){
                      this.$message.success('保存成功');
                    }else{
                      this.$message.error(res.msg);
                    }
                })
            }else{
                actionApi.saveSubActionList(arr).then(res => {
                    if (res.code == 0){
                      this.$message.success('保存成功');
                    }else{
                      this.$message.error(res.msg);
                    }
                })
            }
        },

        ActionClick(data, node) {
            //this.parid = node.parent.id;
            console.log(`点击子环节或服务：${data.actionid} ${data.subactionname} ${node.level} ${this.parid}`);

            if (data.id == -1){
                this.addatree(node,false);
            }else{
            var div=document.getElementById("flagdiv");
            if (data.remarks == 'serv'){

                div.style.display='block';

                actionApi.loadsubaction(data.id).then(res => {
                    if (res.code == 0){
                        console.log(`点击子环节或服务：${res.vsubaction}`);

                        this.fform.id = data.id;
                        this.fform.servAttrFlag = data.servAttrFlag;
                        this.fform.regFlag = data.regFlag;
                        this.fform.subFlag = data.subFlag;
                        this.fform.sumFlag = data.sumFlag;
                        this.fform.module = res.vsubaction.module;
                        this.fform.dependentResource  = res.vsubaction.dependentResource;
                        this.module  = res.vsubaction.module;
                        this.dependentResource  = res.vsubaction.dependentResource;
                        this.flag = [];

                        if (res.vsubaction != null){
                        if (res.vsubaction.servAttrFlag != null && res.vsubaction.servAttrFlag == '1'){
                            this.flag.push('基本属性');
                        }
                        if (res.vsubaction.regFlag != null && res.vsubaction.regFlag == '1'){
                            this.flag.push('注册信息');
                        }
                        if (res.vsubaction.subFlag != null && res.vsubaction.subFlag == '1'){
                            this.flag.push('订阅信息');
                        }
                        if (res.vsubaction.sumFlag != null && res.vsubaction.sumFlag == '1'){
                            this.flag.push('汇总信息');
                        }
                        }

                        console.log(`flag：${this.flag}`);

                        this.editVisible5 = true;
                    }else{
                      this.$message.error(res.msg);
                    }
                })
            }else{
                div.style.display='none';
                this.editVisible5 = false;
                this.fform.id = 0;
                this.flag = [];
            }
            }
        },

        //复选框勾选变化处理代码
        selecteChange(id,checked){
            console.log(`属性变化：${id} ${checked}`);
            var v = checked?1:0;

            if (id == 1){
                this.fform.servAttrFlag = v;
            }else if (id == 2){
                this.fform.regFlag = v;
            }else if (id == 3){
                this.fform.subFlag = v;
            }else if (id == 4){
                this.fform.sumFlag = v;
            }

            actionApi.saveSubaction(this.fform).then(res => {
                 if (res.code == 0){
                   this.$message.success('保存成功');
                 }else{
                   this.$message.error(res.msg);
                 }
               })
        },

        addatree(node,root) {
            console.log(`新增子环节：${node.data.actionid} ${node.data.subactionname} ${node.level}`);

            if (node.level === 1 && root == true){
                this.aform = {};
                this.aform.lvlId = node.data.id;
                this.aform.actionid = node.data.actionid;
                this.aform.subactionname = node.data.subactionname;
                this.aform.remarks = node.data.remarks;
                this.aform.subactionid = node.data.actionid + '_';

                this.editVisible3 = true;
            }else if((node.data.id <= -1  || node.level === 1) && root == false){
                //先用数据库中查询所有服务的列表
                /*if (this.servs.length ==0){
                    actionApi.queryInboundMain().then(res => {
                        if (res.code == 0){
                          this.servs = res.list;
                        }else{
                          this.$message.error(res.msg);
                        }
                    })
                }*/

                this.sform = {};
                this.sform.lvlId = node.data.id;
                this.sform.parentServiceId =  0;
                if(node.data.id > -1)
                    this.sform.subactionid =  node.data.subactionid;
                else
                    this.sform.subactionid =  node.data.actionid;
                this.sform.remarks = 'serv';

                this.editVisible4 = true;
            }else{
                this.sform = {};
                this.sform.lvlId = node.data.id;
                this.sform.subactionid = node.data.actionid;
                this.sform.remarks = node.data.remarks;
                this.sform.parentServiceId = node.data.subactionid;

                this.editVisible4 = true;
            }
        },

        editatree(node) {
           console.log(`编辑子环节：${node.data.actionid} ${node.data.subactionname} ${node.level}`);
           if (node.level === 1){
               this.aform.id = node.data.id;
               this.aform.seq = node.data.seq;
               this.aform.actionid = node.data.actionid;
               this.aform.subactionid = node.data.subactionid;
               this.aform.subactionname = node.data.subactionname;
               this.aform.remarks = node.data.remarks;

               this.editVisible3 = true;
           }
        },
        delatree(node) {
           console.log(`删除子环节：${node.data.actionid} ${node.data.subactionname}`);

           if (node.level === 1){
                actionApi.delAction(node.data.id).then(res => {
                    if (res.code == 0){
                      this.$message.success('删除成功');

                      //刷新
                       node.parent.loaded = false;
                       node.parent.expand();
                    }else{
                      this.$message.error(res.msg);
                    }
                  })
           }else{
                actionApi.delSubAction(node.data.id).then(res => {
                    if (res.code == 0){
                      this.$message.success('删除成功');

                      //刷新
                       node.parent.loaded = false;
                       node.parent.expand();
                    }else{
                      this.$message.error(res.msg);
                    }
                  })
           }
        },
        // 保存环节编辑
        saveEdit() {
            console.log(` ${this.actionid} 增加一个子环节`);
            //this.form.scaid = this.scaid;

            console.log(JSON.stringify(this.aform));
            actionApi.saveAction(this.aform).then(res => {
                 if (res.code == 0){
                    this.$message.success('保存成功');
                     this.editVisible3 = false;
                   //刷新
                   this.refresh(this.actionid);
                 }else{
                   this.$message.error(res.msg);
                 }
               })
        },

        // 保存环节编辑
        saveEdit2() {
            console.log(` 子环节 ${this.scaid} 增加一个关联服务`);
            //this.form.scaid = this.scaid;
            console.log(JSON.stringify(this.sform));
            actionApi.saveSubaction(this.sform).then(res => {
                 if (res.code == 0){
                   this.$message.success('保存成功');
                     this.editVisible4 = false;
                     let currentNode = this.$refs.atreeData.getNode(this.sform.lvlId);
                     currentNode.parent.loaded = false;
                     currentNode.parent.expand();
                   // this.refresh(this.actionid);
                 }else{
                   this.$message.error(res.msg);
                 }
               })
        },

        remoteMethod(query) {
            if (query !== '') {
                // 避免查询多次，在
                clearTimeout(this.remoteTimer);
                this.loading = true;
                this.servs = [];
                this.remoteTimer = setTimeout(() => {
                    this.loading = false;
                    actionApi.queryInboundMainLike(query).then(res => {
                        if (res.code == 0) {
                            this.servs = res.list;
                        }
                        clearTimeout(this.remoteTimer);
                    });
                }, 500);
            } else {
                this.servs = [];
            }
        }
    }
};
</script>

<style lang="scss" scoped>
$iconbg: #a9b1c8;
$borderColor: #e4e7f0;
$actBorderColor: #ffc5b9;
$actColor: #f58e7a;

.wapper {
    display: flex;
    margin: 20px;
    position: relative;
}

.wapper .views-tree {
    width: 700px;
    height: 100%;
}

.wapper .info {
    width: 100px;
    height: 100%;
}

.el-tree {
    margin-top: 20px;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
</style>